<?php
namespace Admin\Model;
use Think\Model;

class SadminModel extends Model {


    public function getSadminByWhere($where,$limit) {
        $where['super'] = array('neq',1);
        $a = session ('admin');
        $where['id'] = array('neq',$a['id']);
        is_null($where) && $where = '';

        return $this->where($where)->limit($limit)->select();
    }


    public function getCountByWhere($where) {
        is_null($where) && $where = '';
        return $this->where($where)->count();
    }


    public function addSadmin($data) {
        $map['account'] = $data['account'];
        $map['email'] = $data['email'];
        $map['_logic'] = 'OR';
        $s = $this->where($map)->find();
        if (!empty($s)) return '100401';

        $flag = $this->add($data);
        if ($flag !== false) return '000000';
        return '111111';
    }


    public function getSadminById($id) {
        return $this->find($id);
    }


    public function editSadmin($data) {
        // 超级管理员不可以修改
        if ($data['id'] == 1) return '111111';

        $map['email'] = $data['email'];
        $map['id'] = array('neq',$data['id']);
        $s = $this->where($map)->find();
        if (!empty($s)) return '100402';

        $flag = $this->save($data);
        if ($flag !== false) return '000000';
        return '111111';
    }


    /**
     * 对editSadmin方法的扩展,提高该方法的扩展性
     * 存在代码重复问题,后期需要整理
     *
     * @param $data
     * @return string
     */
    public function edit($data) {
        // 超级管理员不可以修改
        if ($data['id'] == 1) return '111111';

        $map['email'] = $data['email'];
        $map['id'] = array('neq',$data['id']);
        $s = $this->where($map)->find();
        if (!empty($s)) return '100402';

        $flag = $this->save($data);
        if ($flag !== false) return '000000';
        return '111111';
    }

    public function delSadmin($id) {
        // 超级管理员不可以修改
        if ($id == 1) return '111111';
        $flag = $this->delete($id);
        if ($flag !== false) return '000000';
        return '111111';
    }


    /**
     * 用户登录函数
     *
     * @param $account
     * @param $password
     * @return mixed
     */
    public function login($account, $password) {
        // 邮箱验证正则表达式
        $pattern = '^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+';
        // 正则表达式判断当前是账号登录还是邮箱登录
        ereg ( $pattern, $account ) ? $where ['email'] = $account : $where ['account'] = $account;
        $where ['password'] = md5 ( $password );
        return $this->where ( $where )->find ();
    }
}

